﻿using System;
using System.Diagnostics;
using Kaiser.ConfigManager.Serializers;

namespace Kaiser.ConfigManager
{
    public class ConfigManager<T>
        where T : class
    {

        public ConfigManager()
        {
            //todo need load from ApplicationConfigFile
            _objectSerializer = new XmlObjectSerializer<T>();
        }
        private readonly IObjectSerializer<T> _objectSerializer;

        /// <summary>
        /// get entity direct
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public T Load(string filePath)
        {
            return _objectSerializer.LoadFromFile(filePath);
        }

        /// <summary>
        /// get entity without exception 
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Load(string filePath, out T entity)
        {
            entity = null;
            try
            {
                entity = _objectSerializer.LoadFromFile(filePath);
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return false;
            }
        }

        /// <summary>
        /// save entity to file
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="entity"></param>
        public void Save(string filePath,  T entity)
        {
            _objectSerializer.SaveInFile(filePath,entity);
        }
    }
}
